/* eslint-disable no-undef */
<template>
  <!-- 添加检查项 -->
  <div class="addCheck">
    <el-row>
      <el-col :span="24">
        <el-form :inline="true"
                 :model="proForm">
          <el-form-item label="工序状态">
            <el-input v-model="proForm.processName"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="构件类型">
            <el-input v-model="proForm.componentName"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="检查项名称">
            <el-input v-model="proForm.checkName"
                      disabled></el-input>
          </el-form-item>
          <el-button type="primary"
                     @click="back">
            返回
          </el-button>
          <el-button type="primary"
                     icon="el-icon-plus"
                     @click="addCheckItem">新增</el-button>
        </el-form>
      </el-col>
      <el-col :span="24"
              class="checkItem-col">

        <el-form :inline="true"
                 :inline-message="true"
                 :rules="rules"
                 :model="checkItemList"
                 ref="ruleForm">
          <el-table :data="checkItemList.list"
                    class="checkItem-table"
                    height="510px"
                    :header-cell-style="{background:'#f5f5f5'}"
                    border
                    row-key="check_item_id"
                    :indent="4"
                    :tree-props="{children:'children'}">
            <el-table-column label="参数分类"
                             align="center"
                             show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item class="param-type"
                              :rules='rules.param_type'>
                  <el-select v-model="scope.row.param_type"
                             size="mini">
                    <el-option v-for="item in paramTypeCodeList"
                               :key="item.value"
                               :label="item.name"
                               :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="参数名"
                             align="center"
                             show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item :rules='rules.name'>
                  <el-input v-model="scope.row.name"
                            size="mini"
                            @change="selectCode(scope,1)"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="参数代码"
                             align="center"
                             show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item :rules='rules.key'>
                  <el-input v-model="scope.row.key"
                            size="mini"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="数据类型"
                             align="center"
                             show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item :rules='rules.data_type'>
                  <el-select v-model="scope.row.dataType"
                             value-key="value"
                             size="mini"
                             @change="selectDataType(scope.row)">
                    <el-option v-for="item in dataTypeCodeList"
                               :key="item.value"
                               :label="item.name"
                               :value="item"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="最大长度"
                             align="center"
                             show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item>
                  <el-input-number v-model="scope.row.length"
                                   :min="1"
                                   :controls="false"
                                   size="mini"></el-input-number>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="默认值"
                             align="center"
                             show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item>
                  <el-input v-model="scope.row.default_value"
                            size="mini"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="字段控件"
                             align="center"
                             show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item :rules='rules.control_type'>
                  <el-select v-model="scope.row.controlType"
                             value-key="value"
                             size="mini"
                             @change="selectControlType(scope.row)">
                    <el-option v-for="item in scope.row.controlTypeList"
                               :key="item.value"
                               :label="item.name"
                               :value="item"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="控件配置"
                             align="center"
                             show-overflow-tooltip>
              <template slot-scope="scope">

                <el-form-item>
                  <el-button v-if="scope.row.controlType.content1=='array' || scope.row.controlType.content1=='object'"
                             type="primary"
                             icon="el-icon-plus"
                             size="mini"
                             @click="addChildItem(scope.row,scope.$index,scope)">配置子控件</el-button>
                  <el-button v-if="scope.row.controlType.content1=='listdrop' ||scope.row.controlType.content1=='checkbox'||scope.row.controlType.content1=='radio'"
                             type="primary"
                             icon="el-icon-plus"
                             size="mini"
                             @click="openConfig(scope.$index)">选项配置</el-button>
                  <el-input v-if="scope.row.control_type=='dictionary' "
                            v-model="scope.row.dictionary"
                            size="mini"
                            placeholder="请输入数据字典"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="字段校验"
                             align="center"
                             show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item :rules='rules.check_type'>
                  <el-select v-model="scope.row.checkType"
                             multiple
                             placeholder="请选择"
                             collapse-tags
                             size="mini"
                             @change="selectCheckType(scope.row)">
                    <el-option v-for="item in scope.row.checkTypeList"
                               :key="item.value"
                               :label="item.name"
                               :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="排序"
                             align="center"
                             show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item :rules='rules.sort'>
                  <el-input v-model="scope.row.sort"
                            size="mini"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作"
                             align="center">
              <template slot-scope="scope">
                <el-tooltip content="删除"
                            placement="top">
                  <el-button size="mini"
                             type="info"
                             icon="el-icon-error"
                             @click="deleteRow(scope.$index,checkItemList.list,scope.row.id)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-col>
      <el-col :span="24"
              class="dialog-col">

        <el-button type="success"
                   @click="submitForm('ruleForm')">保 存</el-button>
      </el-col>
    </el-row>

    <!-- <el-dialog title="选项配置"
               :visible.sync="optionConfig"
               :modal="false"
               width="35%">
      <el-table :data="optionData"
                style="width: 100%">
        <el-table-column label="描述"
                         align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.name"
                      size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="值"
                         align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.key"
                      size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column :render-header="renderHeader"
                         align="center">
          <template slot-scope="scope">
            <el-tooltip content="删除"
                        placement="top">
              <el-button size="mini"
                         type="info"
                         icon="el-icon-error"
                         @click="deleteRow(scope.$index,optionData,scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="btn-col">
        <el-button @click="optionConfig=false">取 消</el-button>
        <el-button type="success"
                   @click="submitForm3">保 存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选项配置"
               :visible.sync="optionConfig1"
               :modal="false"
               width="35%">
      <el-table :data="optionChildData"
                style="width: 100%">
        <el-table-column label="描述"
                         align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.name"
                      size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="值"
                         align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.key"
                      size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column :render-header="renderHeader1"
                         align="center">
          <template slot-scope="scope">
            <el-tooltip content="删除"
                        placement="top">
              <el-button size="mini"
                         type="info"
                         icon="el-icon-error"
                         @click="deleteRow(scope.$index,optionChildData,scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="btn-col">
        <el-button @click="optionConfig1=false">取 消</el-button>
        <el-button type="success"
                   @click="submitForm4">保 存</el-button>
      </div>
    </el-dialog> -->
    <AddChildItemDialog :dialogVisible.sync="addChildItemDialogVisible"
                        @callback="addChildCallback"
                        :dialogForm.sync="childItemData"></AddChildItemDialog>
  </div>
</template>
<script>
// 拼音
import 'pinyin4js'
import AddChildItemDialog from './components/AddChildItemDialog'
import { checkItemConfigApi } from '@/services/SystemSetting'
import { standardCodeApi } from '@/services/StandardCode'
export default {
  data () {
    return {
      proForm: {
        state: '',
        type: '',
        project: '',
        proccess_id: '',
        component_type_id: '',
        checkName: '',
        processName: '',
        componentName: '',
        major_id: ''
      },
      ruleForm: {
        tableData: []
      },
      ruleForm1: {
        controlData: []
      },
      ruleForm2: {
        controlChildData: []
      },
      optionData: [{
      }],
      optionChildData: [{
      }],
      add: false,
      optionConfig: false,
      optionConfig1: false,
      addChild: false,
      paramTypeData: [],
      dataType: [],
      select: false,
      select1: false,
      control: '',
      control2: '',
      rules: {
        param_type: [
          { required: true, message: '请选择参数分类', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入参数名', trigger: 'blur' }
        ],
        key: [
          { required: true, message: '请输入参数代码', trigger: 'blur' }
        ],
        data_type: [
          { required: true, message: '请选择数据类型', trigger: 'change' }
        ],
        control_type: [
          { required: true, message: '请选择字段控件', trigger: 'change' }
        ],
        check_type: [
          { required: true, message: '请选择字段校验', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      },
      // 请求检测值列表参数
      requestParam: {
        id: ''
      },
      // 检测值列表数据
      checkItemList: {
        list: []
      },
      // 参数类型标准码列表
      paramTypeCodeList: [],
      // 参数类型标准吗map
      paramTypeMap: new Map(),
      // 数据类型标准码列表
      dataTypeCodeList: [],
      // 数据类型标准码map
      dataTypeMap: new Map(),
      // 字段控件标准码列表
      controlTypeCodeList: [],
      // 字段控件标准码map
      controlTypeMap: new Map(),
      // 校验类型标准码列表
      checkTypeCodeList: [],
      // 校验类型标准码map
      checkTypeMap: new Map(),
      // 配置子控件弹框是否可见
      addChildItemDialogVisible: false,
      // 配置子控件数据对象
      childItemData: [],
      // 当前配置子控件的数据的index
      itemIndex: 0
    }
  },
  components: {
    AddChildItemDialog
  },
  watch: {
    childItemData: {
      handler (newval, oldval) {
        // console.log(newval, this.checkItemList, 'watch')
        // this.checkItemList.list[this.itemIndex].children = newval
      },
      deep: true
    },
    checkItemList: {
      handler (newval, oldval) {
       // console.log(newval, 'watch item list')
      },
      deep: true
    }
  },
  methods: {
    test (row) {
     // console.log(row)
    },
    renderHeader (h) {
      return (
        <div>
          <el-button type='primary' size='mini' onClick={this.addOptions} icon="el-icon-plus"></el-button>
        </div>
      )
    },
    renderHeader1 (h) {
      return (
        <div>
          <el-button type='primary' size='mini' onClick={this.addChildOptions} icon="el-icon-plus"></el-button>
        </div>
      )
    },

    // 新增检查项
    addCheckItem () {
      // 如果没有数据，手动赋值第一个数据的id为1，然后递增
      // 如果已有数据，从最后一个数据的id开始递增
      let checkItemId = 0
      let len = this.checkItemList.list.length
      if (len === 0) {
        checkItemId = 0
      } else {
        checkItemId = +this.checkItemList.list[len - 1].check_item_id + 1
      }
      let item = {
        check_item_id: checkItemId,
        param_type: '',
        name: '',
        key: '',
        data_type: '',
        length: '',
        default_value: '',
        control_type: '',
        check_type: [],
        sort: '',
        children: [],
        check_id: this.requestParam.id,
        major_id: this.requestParam.major_id,
        controlTypeList: [],
        checkTypeList: [],
        controlType: {},
        checkType: {},
        dataType: {}
      }
      this.checkItemList.list.push(item)
    },

    // 新增选项配置
    addOptions () {
      var options = {
        name: '',
        key: '',
        id: ''
      }
      this.optionData.push(options)
    },
    addChildOptions () {
      var options = {
        name: '',
        key: '',
        id: ''
      }
      this.optionChildData.push(options)
    },
    // 参数代码
    selectCode (scope, num) {
      // console.log(scope.$index, scope.row.name, PinyinHelper, 'change')
      let i = scope.$index
      let data = scope.row.name
      scope.row.key = PinyinHelper.getShortPinyin(data)
    },

    deleteRow (index, arr, id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.checkItemList.list.splice(index, 1)
      }).catch(() => {

      })
    },
    // 提交数据
    submitForm (formName) {
     // console.log(this.checkItemList, 'before submit')
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let list = []
          list = JSON.parse(JSON.stringify(this.checkItemList.list))
          list.map((item) => {
            item.children = JSON.stringify(item.children)
          })
          //console.log(list, this.requestParam, 'submit')
          checkItemConfigApi.updateCheckItem({
            data: {
              data: list,
              major_id: this.requestParam.major_id,
              check_id: parseInt(this.$route.query.id)
            }
          }).then(res => {
           // console.log(res, 'add check item')
            if (res.code === 0) {
              this.$message.success('新增成功')
              this.getCheckItemList()
            }
          })
        } else {
          console.log('error submit!!')
        }
      })
      // this.$nextTick(() => {

      // })
    },

    // 配置子控件
    addChildItem (row, index) {
      this.addChildItemDialogVisible = true
      this.itemIndex = this.getIndexByItemId(row.check_item_id)
      this.childItemData = JSON.parse(JSON.stringify(row.children || []))
    },
    // 根据check_item_id获取对应数据的index
    getIndexByItemId (id) {
      let index = -1
      this.checkItemList.list.map((item, ind) => {
        if (item.check_item_id === id) index = ind
      })
      return index
    },
    // 配置子控件成功回调
    addChildCallback (data) {
      let len = this.checkItemList.list.length
      let maxId = this.checkItemList.list[len - 1].check_item_id
      data.list.map((item) => {
        maxId++
        item.check_item_id = maxId + item.name
      })
     // console.log(data, this.checkItemList, this.itemIndex, 'callback')
      // this.checkItemList.list[this.itemIndex].children = data.list
      // data.list[0].check_item_id = 8
      this.$set(this.checkItemList.list[this.itemIndex], 'children', data.list)
    },
    // 数据类型下拉框选中事件
    selectDataType (row) {
      row.data_type = row.dataType.value
      // 根据选中的数据类型筛选出对应的控件类型列表
      row.controlTypeList = this.controlTypeCodeList.filter(item => {
        return row.dataType.content2.includes(item.value)
      })
    },
    // 控件类型下拉框选中事件
    selectControlType (row) {
      row.control_type = row.controlType.value
      // 根据选中的控件类型筛选出对应的校验类型
      row.checkTypeList = this.checkTypeCodeList.filter(item => {
        return row.controlType.content2.includes(item.value)
      })
     // console.log(row, 'select control type')
    },
    // 选择校验类型下拉框选中事件
    selectCheckType (row) {
      row.check_type = row.checkType.join(',')
      //console.log(row)
    },

    // 返回上级
    back () {
      this.$router.push({
        path: '/configure',
        query: {
          id: this.requestParam.major_id
        }
      })
    },
    // 请求检测值列表数据
    getCheckItemList () {
      checkItemConfigApi.getCheckItemList({
        params: this.requestParam
      }).then(res => {
        if (res.code === 0) {
          let list = []
          list = res.data.data
          list.map((item) => {
            item.children = item.children || []
            if (Object.prototype.toString.call(item.children === '[object String]')) {
              item.children = JSON.parse(item.children)
            }
            this.$set(item, 'dataType', this.dataTypeMap.get(item.data_type))
            this.$set(item, 'controlType', this.controlTypeMap.get(item.control_type))
            item.controlTypeList = this.controlTypeCodeList.filter((controlItem) => {
              return item.dataType.content2.includes(controlItem.value)
            })
            this.$set(item, 'checkType', item.check_type.split(''))
            item.checkTypeList = this.checkTypeCodeList.filter((checkItem) => {
              return item.controlType.content2.includes(checkItem.value)
            })
            // item.dataType = this.dataTypeMap.get(item.data_type)
            // item.controlType = this.controlTypeMap.get(item.control_type)
            // item.checkType = this.checkTypeMap.get(item.check_type)
          })
          this.checkItemList.list = list
         // console.log(this.checkItemList.list, 'get checkitem list')
        }
      }, err => {
        console.log(err)
      })
    },
    // 获取参数类型标准码
    getParamTypeCode () {
      standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'param_type'
        }
      }).then(res => {
        console.log(res, 'get param type')
        if (res.code === 0 && res.data.list) {
          this.paramTypeCodeList = res.data.list
          window.localStorage.setItem('paramTypeCode', JSON.stringify(this.paramTypeCodeList))
        }
      })
    },

    // 获取数据类型标准码
    getDataTypeCode () {
      standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'data_type'
        }
      }).then(res => {
      //  console.log(res, 'get data type')
        if (res.code === 0 && res.data.list) {
          this.dataTypeCodeList = res.data.list
          window.localStorage.setItem('dataTypeCode', JSON.stringify(this.dataTypeCodeList))
          this.convertCodeListToMap(this.dataTypeMap, this.dataTypeCodeList)
        }
      })
    },
    // 获取字段控件标准码
    getControlTypeCode () {
      standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'field_control'
        }
      }).then(res => {
       // console.log(res, 'get control type')
        if (res.code === 0 && res.data.list) {
          this.controlTypeCodeList = res.data.list
          window.localStorage.setItem('controlTypeCode', JSON.stringify(this.controlTypeCodeList))
          this.convertCodeListToMap(this.controlTypeMap, this.controlTypeCodeList)
        }
      })
    },
    // 获取字段校验标准码
    getCheckTypeCode () {
      standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'field_check'
        }
      }).then(res => {
       // console.log(res, 'get control type')
        if (res.code === 0 && res.data.list) {
          this.checkTypeCodeList = res.data.list
          window.localStorage.setItem('checkTypeCode', JSON.stringify(this.checkTypeCodeList))
          this.convertCodeListToMap(this.checkTypeMap, this.checkTypeCodeList)
        }
      })
    },
    // 将标准码列表转换为map
    convertCodeListToMap (map, codeList) {
      codeList.map((item) => {
        map.set(item.value, item)
      })
    }
  },
  async created () {
    this.requestParam.id = parseInt(this.$route.query.id)
    this.requestParam.major_id = parseInt(this.$route.query.major_id)
    this.proForm = Object.assign(this.proForm, this.$route.query.checkInfo)
    // 判断是否缓存了标准码数据，是则直接使用缓存，否则请求接口
    let paramTypeCode = window.localStorage.getItem('paramTypeCode')
    let dataTypeCode = window.localStorage.getItem('dataTypeCode')
    let controlTypeCode = window.localStorage.getItem('controlTypeCode')
    let checkTypeCode = window.localStorage.getItem('checkTypeCode')
    if (paramTypeCode) {
      this.paramTypeCodeList = JSON.parse(paramTypeCode)
    } else {
      await this.getParamTypeCode()
    }
    if (dataTypeCode) {
      this.dataTypeCodeList = JSON.parse(dataTypeCode)
      this.convertCodeListToMap(this.dataTypeMap, this.dataTypeCodeList)
    } else {
      await this.getDataTypeCode()
    }
    if (controlTypeCode) {
      this.controlTypeCodeList = JSON.parse(controlTypeCode)
      this.convertCodeListToMap(this.controlTypeMap, this.controlTypeCodeList)
    } else {
      await this.getControlTypeCode()
    }
    if (checkTypeCode) {
      this.checkTypeCodeList = JSON.parse(checkTypeCode)
      this.convertCodeListToMap(this.checkTypeMap, this.checkTypeCodeList)
    } else {
      await this.getCheckTypeCode()
    }
    this.getCheckItemList()
  },
  mounted () {

  }
}
</script>
<style lang="scss" scoped>
.addCheck {
  padding: 15px;
  .checkItem-col {
    text-align: right;
    .checkItem-table {
      width: 100%;
      margin-top: 20px !important;
      .param-type {
        display: block;
      }
    }
  }
  .dialog-col {
    text-align: center;
    margin-top: 20px;
  }
  .btn-col {
    text-align: center;
    margin-top: 20px;
  }
}
</style>
